﻿Public MustInherit Class BaseController
    Inherits System.Web.Mvc.Controller


    Private _repoPediatraAsindo As PediatraAsindoRepository
    Private _saver As ContextSaver

    Protected ReadOnly Property Saver As ContextSaver
        Get
            Return _saver
        End Get
    End Property

    <Ninject.Inject()>
    Public Sub New(ByVal repoPediatraAsindo As PediatraAsindoRepository, ByVal saver As ContextSaver)
        _repoPediatraAsindo = repoPediatraAsindo
        _saver = saver
    End Sub

    Protected Overrides Sub OnActionExecuting(ByVal filterContext As System.Web.Mvc.ActionExecutingContext)

        Dim usuario =
            (From pe
             In _repoPediatraAsindo.All
             Where pe.Usuario = User.Identity.Name
            ).SingleOrDefault

        Dim nombreUsuario As String
        If usuario Is Nothing Then
            nombreUsuario = "Anónimo"
        Else
            nombreUsuario = usuario.NombreCompletoDerecho
        End If
        ViewData("NombreUsuario") = nombreUsuario
        ViewData("Conexión") = Saver.ConnectionString
        MyBase.OnActionExecuting(filterContext)
    End Sub

    Protected MustOverride Sub CargarDatosComunes()
    Protected MustOverride Function VistaFormulario() As String
    Protected MustOverride Function VistaLista() As String

    Protected Function MostrarAux(ByVal obj As Object, vista As String, ByVal titulo As String, Optional ByVal errorMsg As String = "", Optional modal As Boolean = False) As ViewResult
        ModelState.AddModelError("", errorMsg)
        CargarDatosComunes()
        ViewData("Titulo") = titulo
        ViewData("Modal") = modal
        If modal Then
            Return View(vista, "Modal", obj)
        Else
            Return View(vista, obj)
        End If
    End Function
End Class

Public MustInherit Class BaseController(Of T)
    Inherits BaseController

    <Ninject.Inject()>
    Public Sub New(ByVal repoPediatraAsindo As PediatraAsindoRepository, ByVal saver As ContextSaver)
        MyBase.New(repoPediatraAsindo, saver)
    End Sub

    Protected Function Mostrar(ByVal obj As T, ByVal titulo As String, Optional ByVal errorMsg As String = "", Optional modal As Boolean = False) As ViewResult
        Return MostrarAux(obj, VistaFormulario, titulo, errorMsg, modal)
    End Function


    Protected Function Mostrar(ByVal obj As IEnumerable(Of T), ByVal titulo As String) As ViewResult
        Return MostrarAux(obj, VistaLista, titulo)
    End Function

End Class